/**
 * @doc https://github.com/rboulton/libmicrohttpd/blob/master/src/examples/querystring_example.c
 * @brief example for how to get the query string from libmicrohttpd
 *        Call with an URI ending with something like "?sample_number=20"
 * @author xxx
 */

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <microhttpd.h>


int print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value)
{
  printf ("%s: %s\n", key, value);
  return MHD_YES;
}


int connectionHandler (
  void *cls,
  struct MHD_Connection *connection,
  const char *url,
  const char *method,
  const char *version,
  const char *upload_data,
  size_t *upload_data_size,
  void **con_cls)
{
  static int aptr;
  const char *val;

  if (&aptr != *con_cls)
  {
    /* do never respond on first call */
    *con_cls = &aptr;
    return MHD_YES;
  }
  *con_cls = NULL;                  /* reset when done */

  //if (0 != strcmp (method, "GET"))
  //  return MHD_NO;              /* unexpected method */

  //接收参数
  printf("----------------------------------new request------------------------------------------\n");
  printf ("New %s request for %s using version %s; url: %s\n", method, url, version, url);
  MHD_get_connection_values (connection, MHD_HEADER_KIND, print_out_key, NULL);

  //key=value
  val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "sample_number");
  std::cout << val << std::endl;


  //应答
  const char* pageBuffer = "{\"code\": 200, \"msg\": \"success\", \"data\": {}}";
  struct MHD_Response *response;
  response = MHD_create_response_from_buffer(strlen(pageBuffer), (void*)pageBuffer, MHD_RESPMEM_MUST_COPY);

  if (MHD_add_response_header(response, "Content-Type", "application/json") == MHD_NO) {
    std::cout << "MHD_add_response_header error\n";
    return MHD_NO;
  }

  if (MHD_queue_response(connection, MHD_HTTP_OK, response) == MHD_NO) {
    std::cout << "MHD_queue_response error\n";
    return MHD_NO;
  }

  MHD_destroy_response(response);

  return MHD_YES;
}


int main()
{
  const int port = 10185;

  struct MHD_Daemon* daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, port , NULL, NULL, connectionHandler, NULL, MHD_OPTION_END);

  if (daemon == NULL) {
    std::cout << "cannot start server!\n";
    return -1;
  }

  std::cin.get();
  MHD_stop_daemon(daemon);

  return 0;
}

